package ru.spb.osll.myfit.fixtures.base;

import java.util.LinkedList;

import ru.spb.osll.myfit.util.Pair;
import fit.Fixture;
import fit.Parse;

public abstract class MyFitTableFixture extends Fixture {
	private LinkedList<LinkedList<Pair<String, Parse>>> m_cells;

	@Override
	public void doRows(Parse rows) {
		Parse table = rows;
		m_cells = parseCells(table);
		try {
			doStaticTable();
		} catch (Exception e) {
			exception(table, e);	
		}
	}

	private LinkedList<LinkedList<Pair<String, Parse>>> parseCells(Parse rows) {
		LinkedList<LinkedList<Pair<String, Parse>>> result = new LinkedList<LinkedList<Pair<String, Parse>>>();
		Parse row = rows;
		
		while (row != null) {
			result.add(parseRow(row.parts));
			row = row.more;
		}

		return result;
	}
	
	private LinkedList<Pair<String, Parse>> parseRow(Parse rowCells) {
		LinkedList<Pair<String, Parse>> line = new LinkedList<Pair<String, Parse>>();
		while (rowCells != null) {
			if (!rowCells.body.isEmpty() && !rowCells.body.equals("&nbsp;")) {
				line.add(new Pair<String, Parse>(rowCells.body, rowCells));
			}
			rowCells = rowCells.more;
		}
		return line;
	}
	
	protected LinkedList<LinkedList<Pair<String, Parse>>> getCells() {
		return m_cells;
	}

	public abstract void doStaticTable() throws Exception;
}